package com.example.modules.book;

import com.example.generator.mapper.BookMapper;
import com.example.generator.model.Book;
import com.example.utils.Pagination;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
@AllArgsConstructor
public class BookService {
    BookMapper bookMapper;

    public Pagination<BookVO> list(Pagination<BookVO> pagination) {
        PageHelper.startPage(pagination.getPageNo(), pagination.getPageSize());
        List<BookVO> bookVOS = bookMapper.selectFetchAll(pagination);
        pagination.setResult(bookVOS);
        pagination.setCount(((Page<BookVO>) bookVOS).getTotal());
        return pagination;
    }

    public void collect(Integer bookId, Integer userId) {
        long isCollect = bookMapper.isCollect(bookId, userId);
        if (isCollect == 0) {
            bookMapper.collect(bookId, userId);
        } else {
            bookMapper.collectCancel(bookId, userId);
        }
    }

    public Book save(Book bookVO) {
        Book book;
        if (ObjectUtils.isEmpty(bookVO.getId())) {
            book = new Book();
            book.setCreateTime(new Date());
        } else {
            book = bookMapper.selectByPrimaryKey(bookVO.getId());
            book.setUpdateTime(new Date());
        }
        book.setTitle(bookVO.getTitle());
        book.setCode(bookVO.getCode());
        book.setDescription(bookVO.getDescription());
        book.setTotalCount(bookVO.getTotalCount());
        if (ObjectUtils.isEmpty(bookVO.getId())) {
            bookMapper.insertSelective(book);
        } else {
            bookMapper.updateByPrimaryKey(book);
        }
        return book;
    }
}
